<template>
  <view class="music-player" :class="{ 'player-expanded': isExpanded }">
    <!-- 播放器展开视图 -->
    <view v-if="isExpanded" class="player-expanded-view">
      <!-- 背景模糊层 -->
      <image :src="currentSong.cover" class="player-background" mode="aspectFill" />
      <view class="player-overlay"></view>
      
      <!-- 头部控制栏 -->
      <view class="player-header">
        <text class="back-icon" @tap="toggleExpanded">↓</text>
        <text class="player-title">{{ currentSong.name }}</text>
        <text class="favorite-icon" @tap="toggleFavorite">
          {{ isFavorite ? '❤️' : '🤍' }}
        </text>
      </view>
      
      <!-- 唱片区域 -->
      <view class="disc-container">
        <view class="disc" :class="{ 'disc-rotating': isPlaying }">
          <image :src="currentSong.cover" class="disc-image" mode="aspectFill" />
        </view>
      </view>
      
      <!-- 歌曲信息 -->
      <view class="song-info-expanded">
        <text class="song-name-expanded">{{ currentSong.name }}</text>
        <text class="song-artist-expanded">{{ currentSong.artist }}</text>
      </view>
      
      <!-- 进度条 -->
      <view class="progress-container">
        <text class="time-current">{{ formatTime(currentTime) }}</text>
        <view class="progress-bar-expanded">
          <view class="progress-track"></view>
          <view class="progress-fill-expanded" :style="{ width: progressPercentage + '%' }"></view>
          <view class="progress-thumb" :style="{ left: progressPercentage + '%' }"></view>
        </view>
        <text class="time-total">{{ formatTime(currentSong.duration) }}</text>
      </view>
      
      <!-- 控制按钮 -->
      <view class="controls-expanded">
        <text class="control-btn" @tap="playPrev">⏮</text>
        <text class="control-btn play-btn-expanded" @tap="togglePlay">
          {{ isPlaying ? '⏸' : '▶' }}
        </text>
        <text class="control-btn" @tap="playNext">⏭</text>
      </view>
      
      <!-- 播放列表 -->
      <view class="playlist-container">
        <text class="playlist-title">播放列表</text>
        <scroll-view class="playlist-scroll" scroll-y>
          <view 
            v-for="(song, index) in playlist" 
            :key="song.id" 
            class="playlist-item"
            :class="{ 'playlist-item-active': currentSong.id === song.id }"
            @tap="playSong(song)"
          >
            <image :src="song.cover" class="playlist-cover" mode="aspectFill" />
            <view class="playlist-info">
              <text class="playlist-song-name">{{ song.name }}</text>
              <text class="playlist-song-artist">{{ song.artist }}</text>
            </view>
            <text class="playlist-duration">{{ formatTime(song.duration) }}</text>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 播放器收缩视图 -->
    <view v-else class="player-collapsed-view" @tap="toggleExpanded">
      <view class="player-info-collapsed">
        <image :src="currentSong.cover" class="player-cover-collapsed" mode="aspectFill" />
        <view class="player-details-collapsed">
          <text class="player-song-name-collapsed">{{ currentSong.name }}</text>
          <text class="player-artist-collapsed">{{ currentSong.artist }}</text>
        </view>
        <view class="player-controls-collapsed">
          <text class="control-btn-collapsed" @tap.stop="playPrev">⏮</text>
          <text class="control-btn-collapsed play-btn-collapsed" @tap.stop="togglePlay">
            {{ isPlaying ? '⏸' : '▶' }}
          </text>
          <text class="control-btn-collapsed" @tap.stop="playNext">⏭</text>
          <text class="control-btn-collapsed favorite-btn-collapsed" @tap.stop="toggleFavorite">
            {{ isFavorite ? '❤️' : '🤍' }}
          </text>
        </view>
      </view>
      <view class="progress-bar-collapsed">
        <view class="progress-fill-collapsed" :style="{ width: progressPercentage + '%' }"></view>
      </view>
    </view>
  </view>
</template>

<script>
import userManager from '@/utils/user.js'
import mockFavoritesManager from '@/utils/mockFavorites.js'
import historyManager from '@/utils/history.js'

export default {
  name: "musicPlayer",
  data() {
    return {
      isExpanded: false,
      isPlaying: false,
      currentTime: 0,
      progressPercentage: 0,
      audioContext: null,
      isFavorite: false, // 当前歌曲是否已收藏
      playlist: [
        {
          id: 1,
          name: '骄傲',
          artist: '王源',
          cover: 'https://ai-public.mastergo.com/ai/img_res/9b30f4ee0302b8d25ce0fca941c22eca.jpg',
          url: 'https://music.163.com/song/media/outer/url?id=519909355.mp3',
          duration: 240
        },
        {
          id: 2,
          name: '夜的钢琴曲',
          artist: '石进',
          cover: 'https://ai-public.mastergo.com/ai/img_res/c1ce38ecf2bd6fbe61281df433ca6b50.jpg',
          url: 'https://music.163.com/song/media/outer/url?id=139774.mp3',
          duration: 180
        },
        {
          id: 3,
          name: '童话镇',
          artist: '陈一发儿',
          cover: 'https://ai-public.mastergo.com/ai/img_res/f9fc38e361ab67a35c0e5506eddd71df.jpg',
          url: 'https://music.163.com/song/media/outer/url?id=409916250.mp3',
          duration: 210
        },
        {
          id: 4,
          name: '起风了',
          artist: '买辣椒也用券',
          cover: 'https://ai-public.mastergo.com/ai/img_res/45336b12831b6117c08a852940c79512.jpg',
          url: 'https://music.163.com/song/media/outer/url?id=516076896.mp3',
          duration: 195
        }
      ],
      currentSongIndex: 0
    }
  },
  computed: {
    currentSong() {
      return this.playlist[this.currentSongIndex] || this.playlist[0]
    }
  },
  mounted() {
    this.initAudio()
    this.checkFavoriteStatus() // 检查当前歌曲的收藏状态
  },
  beforeDestroy() {
    if (this.audioContext) {
      this.audioContext.destroy()
    }
  },
  methods: {
    initAudio() {
      // 创建音频上下文
      this.audioContext = uni.createInnerAudioContext()
      this.audioContext.src = this.currentSong.url
      
      this.audioContext.onPlay(() => {
        this.isPlaying = true
      })
      
      this.audioContext.onPause(() => {
        this.isPlaying = false
      })
      
      this.audioContext.onEnded(() => {
        this.playNext()
      })
      
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime
        this.progressPercentage = (this.currentTime / this.currentSong.duration) * 100
      })
      
      this.audioContext.onError((err) => {
        console.error('音频播放错误:', err)
        uni.showToast({
          title: '播放失败，请检查网络连接',
          icon: 'none'
        })
      })
    },
    
    togglePlay() {
      if (!this.audioContext) return
      
      if (this.isPlaying) {
        this.audioContext.pause()
      } else {
        this.audioContext.play()
      }
    },
    
    playSong(song) {
      const songIndex = this.playlist.findIndex(s => s.id === song.id)
      if (songIndex !== -1) {
        this.currentSongIndex = songIndex
        this.audioContext.src = song.url
        this.audioContext.play()
        this.onSongChange() // 检查新歌曲的收藏状态
        
        // 添加到播放历史
        this.addToHistory(song)
      }
    },
    
    playPrev() {
      this.currentSongIndex = this.currentSongIndex > 0 ? this.currentSongIndex - 1 : this.playlist.length - 1
      this.audioContext.src = this.currentSong.url
      this.audioContext.play()
      this.onSongChange() // 检查新歌曲的收藏状态
      
      // 添加到播放历史
      this.addToHistory(this.currentSong)
    },
    
    playNext() {
      this.currentSongIndex = this.currentSongIndex < this.playlist.length - 1 ? this.currentSongIndex + 1 : 0
      this.audioContext.src = this.currentSong.url
      this.audioContext.play()
      this.onSongChange() // 检查新歌曲的收藏状态
      
      // 添加到播放历史
      this.addToHistory(this.currentSong)
    },
    
    toggleExpanded() {
      this.isExpanded = !this.isExpanded
    },
    
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    },
    
    seekToPosition(event) {
      if (!this.audioContext || !this.isExpanded) return
      
      // 计算点击位置对应的进度
      const progressBar = event.currentTarget
      const clickX = event.touches[0].clientX
      const barRect = progressBar.getBoundingClientRect()
      const percentage = (clickX - barRect.left) / barRect.width
      
      const targetTime = this.currentSong.duration * percentage
      this.audioContext.seek(targetTime)
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      console.log('=== 收藏功能调试开始 ===')
      console.log('点击收藏按钮')
      
      // 详细检查登录状态
      const isLogin = userManager.checkLogin()
      const userInfo = userManager.getUserInfo()
      const userId = userManager.getUserId()
      
      console.log('登录状态检查结果:', {
        isLogin: isLogin,
        userInfo: userInfo,
        userId: userId,
        userInfoType: typeof userInfo,
        userIdType: typeof userId
      })
      
      // 检查存储状态
      try {
        const storedLogin = uni.getStorageSync('isLogin')
        const storedUserInfo = uni.getStorageSync('userInfo')
        console.log('存储状态检查:', {
          storedLogin: storedLogin,
          storedUserInfo: storedUserInfo,
          storedLoginType: typeof storedLogin
        })
      } catch (error) {
        console.error('检查存储状态失败:', error)
      }
      
      if (!isLogin) {
        console.log('❌ 用户未登录，显示提示')
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      console.log('✅ 用户已登录，继续收藏操作')
      
      try {
        if (this.isFavorite) {
          // 取消收藏
          console.log('🔄 执行取消收藏')
          await this.removeFromFavorites()
        } else {
          // 添加收藏
          console.log('➕ 执行添加收藏')
          await this.addToFavorites()
        }
        console.log('✅ 收藏操作完成')
      } catch (error) {
        console.error('❌ 收藏操作失败:', error)
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
      
      console.log('=== 收藏功能调试结束 ===')
    },
    
    // 添加收藏（虚拟）
    async addToFavorites() {
      const userId = userManager.getUserId()
      console.log('添加收藏 - 用户ID:', userId)
      console.log('添加收藏 - 歌曲信息:', this.currentSong)
      
      try {
        mockFavoritesManager.addFavorite(userId, this.currentSong)
        this.isFavorite = true
        console.log('收藏添加成功')
        uni.showToast({
          title: '已添加到收藏',
          icon: 'success'
        })
      } catch (error) {
        console.error('添加收藏失败:', error)
        throw new Error(error.message)
      }
    },
    
    // 取消收藏（虚拟）
    async removeFromFavorites() {
      const userId = userManager.getUserId()
      const songId = this.currentSong.id
      
      try {
        mockFavoritesManager.removeFavorite(userId, songId)
        this.isFavorite = false
        uni.showToast({
          title: '已取消收藏',
          icon: 'success'
        })
      } catch (error) {
        throw new Error(error.message)
      }
    },
    
    // 检查当前歌曲是否已收藏（虚拟）
    async checkFavoriteStatus() {
      if (!userManager.checkLogin()) {
        this.isFavorite = false
        return
      }
      
      try {
        const userId = userManager.getUserId()
        this.isFavorite = mockFavoritesManager.isFavorite(userId, this.currentSong.id)
      } catch (error) {
        console.error('检查收藏状态失败:', error)
        this.isFavorite = false
      }
    },
    
    // 当歌曲切换时检查收藏状态
    onSongChange() {
      this.checkFavoriteStatus()
    },
    
    // 添加到播放历史
    addToHistory(song) {
      if (!userManager.checkLogin()) {
        return // 未登录用户不记录播放历史
      }
      
      try {
        const userId = userManager.getUserId()
        const songInfo = {
          songId: song.id,
          songTitle: song.name,
          artist: song.artist,
          coverUrl: song.cover
        }
        historyManager.addToHistory(userId, songInfo)
      } catch (error) {
        console.error('添加播放历史失败:', error)
      }
    },
    
    // 隐藏搜索结果（兼容性方法）
    hideSearchResults() {
      // 空实现，保持兼容性
    }
  }
}
</script>

<style scoped>
.music-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
}

/* 收缩状态样式 */
.player-collapsed-view {
  background: rgba(255, 255, 255, 0.95);
  color: #4a6b4a;
  border-radius: 20rpx 20rpx 0 0;
  box-shadow: 0 -4rpx 20rpx rgba(74, 107, 74, 0.15);
  margin: 0 20rpx;
  backdrop-filter: blur(10px);
}

.player-info-collapsed {
  display: flex;
  align-items: center;
  padding: 16rpx 32rpx;
  height: 120rpx;
}

.player-cover-collapsed {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
}

.player-details-collapsed {
  flex: 1;
  min-width: 0;
}

.player-song-name-collapsed {
  font-size: 28rpx;
  font-weight: 500;
  color: #4a6b4a;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.player-artist-collapsed {
  font-size: 24rpx;
  color: #6b8e6b;
  margin-top: 8rpx;
  display: block;
}

.player-controls-collapsed {
  display: flex;
  align-items: center;
  gap: 32rpx;
}

.control-btn-collapsed {
  font-size: 32rpx;
  padding: 8rpx;
  color: #6b8e6b;
  opacity: 0.8;
  transition: all 0.2s ease;
}

.play-btn-collapsed {
  font-size: 40rpx;
  color: #4a6b4a;
}

.favorite-btn-collapsed {
  font-size: 32rpx;
  color: #ff6b6b;
}

.progress-bar-collapsed {
  height: 4rpx;
  background-color: #e8f5e8;
  border-radius: 2rpx;
  margin: 0 32rpx 16rpx;
}

.progress-fill-collapsed {
  height: 100%;
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  border-radius: 2rpx;
  transition: width 0.3s ease;
}

/* 展开状态样式 */
.player-expanded {
  height: 100vh;
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
}

.player-expanded-view {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.player-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: blur(20px);
  opacity: 0.4;
}

.player-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(240, 248, 240, 0.8);
}

.player-header {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 80rpx 32rpx 32rpx;
  color: #4a6b4a;
}

.back-icon, .favorite-icon {
  font-size: 36rpx;
  padding: 16rpx;
  color: #6b8e6b;
}

.player-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #4a6b4a;
}

.disc-container {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: center;
  margin: 80rpx 0;
}

.disc {
  width: 500rpx;
  height: 500rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  animation: rotate 20s linear infinite;
  animation-play-state: paused;
  box-shadow: 0 8rpx 32rpx rgba(74, 107, 74, 0.3);
}

.disc-rotating {
  animation-play-state: running;
}

.disc-image {
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.song-info-expanded {
  position: relative;
  z-index: 1;
  text-align: center;
  color: #4a6b4a;
  margin-bottom: 80rpx;
}

.song-name-expanded {
  font-size: 48rpx;
  font-weight: 600;
  display: block;
  color: #4a6b4a;
}

.song-artist-expanded {
  font-size: 32rpx;
  color: #6b8e6b;
  margin-top: 16rpx;
  display: block;
}

.progress-container {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  margin-bottom: 80rpx;
  color: #4a6b4a;
}

.time-current, .time-total {
  font-size: 24rpx;
  color: #6b8e6b;
  width: 80rpx;
}

.progress-bar-expanded {
  flex: 1;
  height: 4rpx;
  background-color: rgba(107, 142, 107, 0.3);
  margin: 0 32rpx;
  position: relative;
  border-radius: 2rpx;
}

.progress-track {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.progress-fill-expanded {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  transition: width 0.3s ease;
  border-radius: 2rpx;
}

.progress-thumb {
  position: absolute;
  top: 50%;
  width: 20rpx;
  height: 20rpx;
  background-color: #4a6b4a;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 2rpx 8rpx rgba(74, 107, 74, 0.3);
}

.controls-expanded {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 80rpx;
  margin-bottom: 80rpx;
}

.control-btn {
  font-size: 48rpx;
  color: #4a6b4a;
  padding: 16rpx;
  opacity: 0.8;
  transition: all 0.2s ease;
}

.play-btn-expanded {
  font-size: 80rpx;
  color: #4a6b4a;
}

.playlist-container {
  position: relative;
  z-index: 1;
  flex: 1;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 32rpx 32rpx 0 0;
  padding: 32rpx;
  backdrop-filter: blur(10px);
}

.playlist-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #4a6b4a;
  margin-bottom: 32rpx;
  display: block;
}

.playlist-scroll {
  height: 400rpx;
}

.playlist-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  background: rgba(107, 142, 107, 0.1);
}

.playlist-item-active {
  background: rgba(107, 142, 107, 0.2);
}

.playlist-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
}

.playlist-info {
  flex: 1;
  min-width: 0;
}

.playlist-song-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #4a6b4a;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.playlist-song-artist {
  font-size: 24rpx;
  color: #6b8e6b;
  margin-top: 8rpx;
  display: block;
}

.playlist-duration {
  font-size: 24rpx;
  color: #6b8e6b;
  margin-left: 24rpx;
}
</style>